<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>生成报关单</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="goBack">返回</el-button>
      </div>

      <!-- 选中订单信息 -->
      <el-descriptions title="选中订单信息" :column="1" border style="margin-bottom: 20px;">
        <el-descriptions-item label="选中订单数量">{{ selectedOrders.length }} 个</el-descriptions-item>
        <el-descriptions-item label="订单总金额">{{ totalAmount.toFixed(2) }} USD</el-descriptions-item>
      </el-descriptions>

      <!-- 选中订单列表 -->
      <el-table :data="selectedOrders" style="width: 100%; margin-bottom: 20px;" border>
        <el-table-column prop="orderNo" label="订单号" width="140"></el-table-column>
        <el-table-column prop="platformOrderNo" label="平台订单号" width="140"></el-table-column>
        <el-table-column prop="customerName" label="客户姓名" width="120"></el-table-column>
        <el-table-column prop="totalAmount" label="订单金额" width="100" align="right">
          <template slot-scope="scope">
            {{ scope.row.currency }} {{ scope.row.totalAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="orderStatus" label="订单状态" width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.fiscale_order_status" :value="scope.row.orderStatus"/>
          </template>
        </el-table-column>
        <el-table-column prop="customsStatus" label="报关状态" width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.fiscale_customs_status" :value="scope.row.customsStatus"/>
          </template>
        </el-table-column>
      </el-table>

      <!-- 报关单生成表单 -->
      <el-form ref="customsForm" :model="customsForm" :rules="customsRules" label-width="120px">
        <h3>报关单信息</h3>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="报关单类型" prop="declarationType">
              <el-select v-model="customsForm.declarationType" placeholder="请选择报关单类型" style="width: 100%;">
                <el-option label="出口报关单" value="export"></el-option>
                <el-option label="进口报关单" value="import"></el-option>
                <el-option label="转关报关单" value="transfer"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="贸易方式" prop="tradeMode">
              <el-select v-model="customsForm.tradeMode" placeholder="请选择贸易方式" style="width: 100%;">
                <el-option label="一般贸易" value="general"></el-option>
                <el-option label="加工贸易" value="processing"></el-option>
                <el-option label="保税仓库" value="bonded"></el-option>
                <el-option label="跨境电商" value="cross_border"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="运输方式" prop="transportMode">
              <el-select v-model="customsForm.transportMode" placeholder="请选择运输方式" style="width: 100%;">
                <el-option label="空运" value="air"></el-option>
                <el-option label="海运" value="sea"></el-option>
                <el-option label="陆运" value="land"></el-option>
                <el-option label="邮政" value="post"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="启运港" prop="departurePort">
              <el-input v-model="customsForm.departurePort" placeholder="请输入启运港"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="目的港" prop="destinationPort">
              <el-input v-model="customsForm.destinationPort" placeholder="请输入目的港"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预计出口日期" prop="exportDate">
              <el-date-picker
                v-model="customsForm.exportDate"
                type="date"
                placeholder="选择预计出口日期"
                style="width: 100%;"
                value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注信息" prop="remark">
          <el-input
            v-model="customsForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息">
          </el-input>
        </el-form-item>

        <!-- 操作按钮 -->
        <div style="text-align: center; margin-top: 30px;">
          <el-button type="primary" @click="submitForm" :loading="submitting">生成报关单</el-button>
          <el-button @click="goBack">取消</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { listOrder } from "@/api/fiscale/order";
import { createDeclarationFromOrders } from "@/api/fiscale/declaration";

export default {
  name: "CustomsDeclarationCreate",
  dicts: ['fiscale_order_status', 'fiscale_customs_status'],
  data() {
    return {
      // 选中的订单
      selectedOrders: [],
      // 总金额
      totalAmount: 0,
      // 提交状态
      submitting: false,
      // 报关单表单
      customsForm: {
        declarationType: '',
        tradeMode: '',
        transportMode: '',
        departurePort: '',
        destinationPort: '',
        exportDate: '',
        remark: ''
      },
      // 表单验证规则
      customsRules: {
        declarationType: [
          { required: true, message: '请选择报关单类型', trigger: 'change' }
        ],
        tradeMode: [
          { required: true, message: '请选择贸易方式', trigger: 'change' }
        ],
        transportMode: [
          { required: true, message: '请选择运输方式', trigger: 'change' }
        ],
        departurePort: [
          { required: true, message: '请输入启运港', trigger: 'blur' }
        ],
        destinationPort: [
          { required: true, message: '请输入目的港', trigger: 'blur' }
        ],
        exportDate: [
          { required: true, message: '请选择预计出口日期', trigger: 'change' }
        ]
      }
    };
  },
  created() {
    this.loadSelectedOrders();
  },
  methods: {
    /** 加载选中的订单 */
    loadSelectedOrders() {
      const orderIds = this.$route.query.orderIds;
      if (!orderIds) {
        this.$modal.msgError("未找到选中的订单信息");
        this.goBack();
        return;
      }

      const orderIdArray = orderIds.split(',');
      
      // 构建查询参数 - 使用订单ID列表
      const queryParams = {
        pageNum: 1,
        pageSize: 100, // 设置足够大的页面大小
        orderIds: orderIdArray.join(',')
      };

      listOrder(queryParams).then(response => {
        this.selectedOrders = response.rows || [];
        this.calculateTotalAmount();
        
        if (this.selectedOrders.length === 0) {
          this.$modal.msgError("未找到有效的订单数据");
          this.goBack();
        }
      }).catch(error => {
        console.error('加载订单数据失败:', error);
        this.$modal.msgError("加载订单数据失败");
        this.goBack();
      });
    },
    
    /** 计算总金额 */
    calculateTotalAmount() {
      this.totalAmount = this.selectedOrders.reduce((total, order) => {
        return total + (parseFloat(order.totalAmount) || 0);
      }, 0);
    },
    
    /** 提交表单 */
    submitForm() {
      this.$refs["customsForm"].validate(valid => {
        if (valid) {
          this.submitting = true;
          
          // 构建报关单数据
          const customsData = {
            ...this.customsForm,
            orderIds: this.selectedOrders.map(order => order.orderId),
            orderNos: this.selectedOrders.map(order => order.orderNo),
            totalAmount: this.totalAmount,
            currency: 'USD'
          };
          
          // 调用生成报关单API
          createDeclarationFromOrders(customsData).then(response => {
            this.submitting = false;
            this.$modal.msgSuccess("报关单生成成功！");
            
            // 跳转到成功页面，传递生成结果信息
            const resultData = response.data || {};
            this.$router.push({
              path: '/fiscale/customs/declaration/success',
              query: {
                declarationId: resultData,
                orderIds: this.selectedOrders.map(order => order.orderId).join(',')
              }
            });
          }).catch(error => {
            this.submitting = false;
            console.error('生成报关单失败:', error);
            this.$modal.msgError("生成报关单失败：" + (error.msg || '系统错误'));
          });
          
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    },
    
    /** 返回订单列表 */
    goBack() {
      this.$router.push('/fiscale/order-management/order-list');
    }
  }
};
</script>

<style scoped>
h3 {
  color: #409EFF;
  border-bottom: 2px solid #409EFF;
  padding-bottom: 10px;
  margin-bottom: 20px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}
</style>